The goals / steps of this project are the following:
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib qt
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*9,3), np.float32)
objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.
# Make a list of calibration images
chess_images = glob.glob('camera_cal/calibration*.jpg')
# Step through the list and search for chessboard corners
for fname in chess_images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (9,6),None)
# If found, add object points, image points
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
# Draw and display the corners
img = cv2.drawChessboardCorners(img, (9,6), corners, ret)
cv2.imshow('img',img)
cv2.waitKey(500)
cv2.destroyAllWindows()
# Function for undistortion of any image
def undistort(img, objpoints, imgpoints):
img_size = (img.shape[1], img.shape[0])
# take calibration constants
ret, mtx, dist, rvecs, tcevs = cv2.calibrateCamera(objpoints, imgpoints, img_size,None,None)
# use the camera matrix (mtx) and distortion coefficients (dist) for undistortion
undist=cv2.undistort(img, mtx, dist, None, mtx)
return undist
%matplotlib inline
# show an example for a undistorted Chessboard image
src_dir = 'camera_cal/'
example='calibration1.jpg'
# Read and undistort Chessboard image
img = mpimg.imread(src_dir+example)
undistorted = undistort(img, objpoints, imgpoints)
# Show result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(undistorted)
ax2.set_title('Undistorted Chessboard Image', fontsize=30)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# save undistorted images in output_images directory
src_dir = 'test_images/'
dst_dir = 'output_images/undistorted/'
raw_images = glob.glob(src_dir+'*.jpg')
for image in raw_images:
img=undistort(cv2.imread(image), objpoints, imgpoints)
cv2.imwrite(dst_dir+image[12:], img)
# show an example for an undistorted road image
src_dir = 'test_images/'
dst_dir = 'output_images/undistorted/'
example = 'straight_lines1.jpg'
# Read images
src_img = mpimg.imread(src_dir+example)
dst_img = mpimg.imread(dst_dir+example)
# Show result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))
ax1.imshow(src_img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(dst_img)
ax2.set_title('Undistorted Image', fontsize=30)
# To see all the samples at the same line
def show_examples(jpg_dir):
src_source = glob.glob(jpg_dir+'*.jpg')
src_images=[]
for i in range(len(src_source)):
src_images.append(mpimg.imread(src_source[i]))
# plot the images
fig = plt.figure(figsize=(20, 10))
for idx in np.arange(8):
ax1 = fig.add_subplot(1, 8, idx+1, xticks=[], yticks=[])
plt.imshow(src_images[idx])
del src_images
src_dir = 'test_images/'
dst_dir = 'output_images/undistorted/'
show_examples(src_dir)
show_examples(dst_dir)
# Include threshold mask functions from the threshold file
from thresholds import *
# chose the best combination of masks
def thmask(img):
absolute_sobel_x = abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh=(20, 100))
color_hls_S = hls_select(img, channel='S', thresh=(90, 255))
combined_binary = np.zeros_like(absolute_sobel_x)
combined_binary[(color_hls_S == 1) | (absolute_sobel_x == 1)] = 1
combined_img = np.dstack(( combined_binary, combined_binary, combined_binary))*255
return combined_img
# save undistorted-thresholded images in output_images directory
src_dir = 'output_images/undistorted/'
dst_dir = 'output_images/undistorted-thresholded/'
raw_images = glob.glob(src_dir+'*.jpg')
for image in raw_images:
img = thmask(cv2.imread(image))
cv2.imwrite(dst_dir+image[26:], img)
# show an example for an undistorted-thresholded image
src_dir = 'output_images/undistorted/'
example = 'test6.jpg'
# Read image
src_img = mpimg.imread(src_dir+example)
# Show result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))
ax1.imshow(src_img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(thmask(src_img))
ax2.set_title('Undistorted-thresholded Image', fontsize=30)
# corners for source
src = np.float32([[[679, 447], # top right (x,y)
[1090,700], # bottom right (x,y)
[225, 700], # bottom left (x,y)
[600, 447]]]) # top left (x,y)
# corners for destination
dst = np.float32([[[850, 0], # top right (x,y)
[850, 720], # bottom right (x,y)
[250, 720], # bottom left (x,y)
[250, 0]]]) # top left (x,y)
# make a function for Perspective Transform
def p_transfer(img, src, dst):
img_size = (img.shape[1], img.shape[0])
# calculate the perspective transform matrix
M = cv2.getPerspectiveTransform(src, dst)
# return warped image
warped = cv2.warpPerspective(img, M, img_size)
return warped
# save undistorted-transformed images in output_images directory
src_dir = 'output_images/undistorted/'
dst_dir = 'output_images/undistorted-transformed/'
raw_images = glob.glob(src_dir+'*.jpg')
for image in raw_images:
img = p_transfer(cv2.imread(image), src,dst)
cv2.imwrite(dst_dir+image[26:], img)
# show an example for an undistorted-transformed image
src_dir = 'output_images/undistorted/'
dst_dir = 'output_images/undistorted-transformed/'
example = 'straight_lines1.jpg'
# Read images
src_img = mpimg.imread(src_dir+example)
dst_img = mpimg.imread(dst_dir+example)
# Show transfer boundaries from the source image to the destination image
cv2.polylines(dst_img, np.int32(dst),False,(255,0,0),3)
cv2.polylines(src_img, np.int32(src),True,(255,0,0),3)
# Show result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(src_img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(dst_img)
ax2.set_title('Undistorted and Warped Image', fontsize=30)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# save undistorted-transformed images in output_images directory
src_dir = 'output_images/undistorted-transformed/'
dst_dir = 'output_images/undistorted-transformed-thresholded/'
raw_images = glob.glob(src_dir+'*.jpg')
for image in raw_images:
img = thmask(cv2.imread(image))
cv2.imwrite(dst_dir+image[len(src_dir):], img)
# Show transformed and thresholded images
src_dir_1 = 'output_images/undistorted/'
src_dir_2 = 'output_images/undistorted-transformed/'
dst_dir = 'output_images/undistorted-transformed-thresholded/'
show_examples(src_dir_1)
show_examples(src_dir_2)
show_examples(dst_dir)
# for detecting line instead Houghlines
def line_finder(binary_warped, h=25000):
# Take a histogram of the bottom half of the image
histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)
# Create an output image to draw on and visualize the result
out_img = np.dstack((binary_warped, binary_warped, binary_warped))
# Find the peak of the left and right halves of the histogram
# These will be the starting point for the left and right lines
midpoint = np.int(histogram.shape[0]//2)
if histogram[:midpoint].max() > h:
left = True
else:
left = False
if histogram[midpoint:].max() > h:
right = True
else:
right = False
return left, right
def find_lane_pixels(binary_warped):
# Take a histogram of the bottom half of the image
histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)
# Create an output image to draw on and visualize the result
out_img = np.dstack((binary_warped, binary_warped, binary_warped))
# Find the peak of the left and right halves of the histogram
# These will be the starting point for the left and right lines
midpoint = np.int(histogram.shape[0]//2)
h=25000
# if both lines realy found
if histogram[:midpoint].max() > h and histogram[midpoint:].max() > h:
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
# if just left-line really found, you can start searching the right-line that n pixel right
elif histogram[:midpoint].max() > h and histogram[midpoint:].max() < h:
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = leftx_base+580 # seperation of lines in px is ~580
# if just right line realy found, you can start searching the left-line that n pixel right
elif histogram[:midpoint].max() > h and histogram[midpoint:].max() > h:
leftx_base = rightx_base+580
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
# for avoid error
else:
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
# HYPERPARAMETERS
# Choose the number of sliding windows
nwindows = 9
# Set the width of the windows +/- margin
margin = 100
# Set minimum number of pixels found to recenter window
minpix = 50
# Set height of windows - based on nwindows above and image shape
window_height = np.int(binary_warped.shape[0]//nwindows)
# Identify the x and y positions of all nonzero pixels in the image
nonzero = binary_warped.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Current positions to be updated later for each window in nwindows
leftx_current = leftx_base
rightx_current = rightx_base
# Create empty lists to receive left and right lane pixel indices
left_lane_inds = []
right_lane_inds = []
# Step through the windows one by one
for window in range(nwindows):
# Identify window boundaries in x and y (and right and left)
win_y_low = binary_warped.shape[0] - (window+1)*window_height
win_y_high = binary_warped.shape[0] - window*window_height
# Find the four below boundaries of the window ###
win_xleft_low = leftx_current-margin
win_xleft_high = leftx_current+margin
win_xright_low = rightx_current-margin
win_xright_high = rightx_current+margin
# Draw the windows on the visualization image
cv2.rectangle(out_img,(win_xleft_low,win_y_low),
(win_xleft_high,win_y_high),(0,255,0), 2)
cv2.rectangle(out_img,(win_xright_low,win_y_low),
(win_xright_high,win_y_high),(0,255,0), 2)
# Identify the nonzero pixels in x and y within the window #
good_left_inds = ((nonzeroy>=win_y_low)&(nonzeroy<win_y_high)&
(nonzerox>=win_xleft_low)&(nonzerox<win_xleft_high)).nonzero()[0]
good_right_inds = ((nonzeroy>=win_y_low)&(nonzeroy<win_y_high)&
(nonzerox>=win_xright_low)&(nonzerox<win_xright_high)).nonzero()[0]
# Append these indices to the lists
left_lane_inds.append(good_left_inds)
right_lane_inds.append(good_right_inds)
# If you found > minpix pixels, recenter next window
if len(good_left_inds) > minpix:
leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
if len(good_right_inds) > minpix:
rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
# Concatenate the arrays of indices (previously was a list of lists of pixels)
try:
left_lane_inds = np.concatenate(left_lane_inds)
right_lane_inds = np.concatenate(right_lane_inds)
except ValueError:
# Avoids an error if the above is not implemented fully
pass
# Extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
return leftx, lefty, rightx, righty, out_img
def fit_polynomial(binary_warped, draw_line=True):
# Find our lane pixels first
leftx, lefty, rightx, righty, out_img = find_lane_pixels(binary_warped)
# Fit a second order polynomial
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
# Generate x and y values for plotting
ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])
try:
left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
except TypeError:
# Avoids an error if `left` and `right_fit` are still none or incorrect
left_fitx = 1*ploty**2 + 1*ploty
right_fitx = 1*ploty**2 + 1*ploty
## Visualization ##
# Colors in the left and right lane regions
out_img[lefty, leftx] = [255, 0, 0]
out_img[righty, rightx] = [0, 0, 255]
if draw_line:
# Plots the left and right polynomials on the lane lines
plt.plot(left_fitx, ploty, color='yellow', linewidth=4)
plt.plot(right_fitx, ploty, color='yellow', linewidth=4)
plt.xlim(0, 1280)
plt.ylim(720, 0)
return out_img
def hist(img):
img_size = img.shape
bottom_half = img[img_size[0]//2:,:]
histogram = np.sum(bottom_half, axis=0)
return histogram
# Show an example for windowed lane line
img = mpimg.imread('output_images/undistorted-transformed-thresholded/test6.jpg')
binary_warped = img[:,:,1]
# Show result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(fit_polynomial(binary_warped,True))
ax2.set_title('Image with windows', fontsize=30)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
plt.plot(hist(img))
# save undistorted-transformed-thresholded-windowed images in output_images directory
src_dir = 'output_images/undistorted-transformed-thresholded/'
dst_dir = 'output_images/undistorted-transformed-thresholded-windowed/'
raw_images = glob.glob(src_dir+'*.jpg')
for image in raw_images:
binary_warped = cv2.imread(image)[:,:,1]
img = fit_polynomial(binary_warped, False)
cv2.imwrite(dst_dir+image[len(src_dir):], img)
# show undistorted-transformed-thresholded-windowed images in output_images directory
src_dir_1 = 'output_images/undistorted/'
src_dir_2 = 'output_images/undistorted-transformed/'
src_dir_3 = 'output_images/undistorted-transformed-thresholded/'
dst_dir = 'output_images/undistorted-transformed-thresholded-windowed/'
#show_examples(src_dir_1)
show_examples(src_dir_2)
show_examples(src_dir_3)
show_examples(dst_dir)
def search_around_poly(binary_warped, draw_line=True):
# Find our lane pixels first
leftx, lefty, rightx, righty, _ = find_lane_pixels(binary_warped)
# Fit a second order polynomial
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
# HYPERPARAMETER
margin = 100
# Grab activated pixels
nonzero = binary_warped.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Set the area of search based on activated x-values within the +/- margin of our polynomial function
left_x = left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2]
right_x = right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2]
left_lane_inds = ((nonzerox > (left_x - margin)) & (nonzerox < left_x + margin))
right_lane_inds = ((nonzerox > (right_x - margin)) & (nonzerox < right_x + margin))
# Again, extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
# Fit new polynomials
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
# Generate x and y values for plotting
ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])
#Calc both polynomials
left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
## Visualization ##
# Create an image to draw on and an image to show the selection window
out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255
window_img = np.zeros_like(out_img)
# Color in left and right line pixels
out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]
# Generate a polygon to illustrate the search window area
# And recast the x and y points into usable format for cv2.fillPoly()
left_line_window1 = np.array([np.transpose(np.vstack([left_fitx-margin, ploty]))])
left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx+margin, ploty])))])
left_line_pts = np.hstack((left_line_window1, left_line_window2))
right_line_window1 = np.array([np.transpose(np.vstack([right_fitx-margin, ploty]))])
right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx+margin, ploty])))])
right_line_pts = np.hstack((right_line_window1, right_line_window2))
# Draw the lane onto the warped blank image
cv2.fillPoly(window_img, np.int_([left_line_pts]), (0,255, 0))
cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0))
result = cv2.addWeighted(out_img, 1, window_img, 0.3, 0)
if draw_line:
# Plot the polynomial lines onto the image
plt.plot(left_fitx, ploty, color='yellow')
plt.plot(right_fitx, ploty, color='yellow')
return result
# Show an example for windowed lane line
img = mpimg.imread('output_images/undistorted-transformed-thresholded/test6.jpg')
binary_warped = img[:,:,1]
# Show result
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(search_around_poly(binary_warped, True))
ax2.set_title('Lane Lines in Pipes', fontsize=30)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
# save undistorted-transformed-thresholded-pipe images in output_images directory
src_dir = 'output_images/undistorted-transformed-thresholded/'
dst_dir = 'output_images/undistorted-transformed-thresholded-pipe/'
raw_images = glob.glob(src_dir+'*.jpg')
for image in raw_images:
binary_warped = cv2.imread(image)[:,:,1]
img = search_around_poly(binary_warped, False)
cv2.imwrite(dst_dir+image[len(src_dir):], img)
src_dir_1 = 'output_images/undistorted/'
src_dir_2 = 'output_images/undistorted-transformed/'
src_dir_3 = 'output_images/undistorted-transformed-thresholded/'
src_dir_4 = 'output_images/undistorted-transformed-thresholded-windowed/'
dst_dir = 'output_images/undistorted-transformed-thresholded-pipe/'
#show_examples(src_dir_1)
#show_examples(src_dir_2)
show_examples(src_dir_3)
show_examples(src_dir_4)
show_examples(dst_dir)
# Define a class to receive the characteristics of each line detection
class Line():
def __init__(self):
# was the line detected in the last iteration?
self.detected = False
#radius of curvature of the line in some units
self.radius_of_curvature = []
#distance in meters of vehicle center from the line
self.line_base_pos = []
# mean of current x coordinates of line
self.currentx_mean = 600
# mean of last x coordinates of line
self.lastx_mean = 600
#x values for detected line pixels
self.allx = []
#y values for detected line pixels
self.ally = []
# x values of the last n fits of the line
self.recent_xfitted = [np.array([False])]
# create two instances for left and right lines
left_cls = Line()
right_cls = Line()
def radii_offset(binary_warped):
# Define conversions in x and y from pixels space to meters
# There are 3 dashed lane lines and approximately 4 empty spaces between them in the thresholded pictures.
# 3 dashed lines = 30ft, 4 empty places = 120px. That means 720px~150feet~45meter
ym_per_pix = 45/720 # meters per pixel in y dimension
# Distance between two parallel lane lines is approximately 580px in the thresholded pictures
xm_per_pix = 3.7/580 # meters per pixel in x dimension
#ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])
leftx, lefty, rightx, righty, _ = find_lane_pixels(binary_warped)
#ploty = ploty*ym_per_pix
leftx = leftx*xm_per_pix
rightx = rightx*xm_per_pix
lefty = lefty*ym_per_pix
righty = righty*ym_per_pix
# Fit a second order polynomial
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
# Define y-value where we want radius of curvature
# We'll choose the maximum y-value, corresponding to the bottom of the image
y_eval = binary_warped.shape[0]*ym_per_pix
# R_curve (radius of curvature)
# left line
left_curverad = np.sqrt(np.power(1+(2*left_fit[0]*y_eval+left_fit[1])**2,3))/np.abs(2*left_fit[0])
# right line
right_curverad = np.sqrt(np.power(1+(2*right_fit[0]*y_eval+right_fit[1])**2,3))/np.abs(2*right_fit[0])
x= (binary_warped.shape[1]*xm_per_pix)
y= (binary_warped.shape[0]*ym_per_pix)
# find x coordinate of camera
camera_x = x/2
# find x coordinates of lines
left_line_x = (left_fit[0]*y**2 + left_fit[1]*y + left_fit[2])
right_line_x = (right_fit[0]*y**2 + right_fit[1]*y + right_fit[2])
# Accumulate values of curverad and line base positions
left_cls.line_base_pos.append(abs(camera_x-left_line_x))
right_cls.line_base_pos.append(abs(camera_x-right_line_x))
# don't save the curv. info when lane-line is not clear
left_cls.detected, right_cls.detected = line_finder(img, h=2500)
if left_cls.detected and right_cls.detected:
left_cls.radius_of_curvature.append(left_curverad)
right_cls.radius_of_curvature.append(right_curverad)
elif left_cls.detected and not right_cls.detected:
left_cls.radius_of_curvature.append(left_curverad)
# left lines info is useful when right line is none.
right_cls.radius_of_curvature.append(left_curverad)
elif not left_cls.detected and right_cls.detected:
right_cls.radius_of_curvature.append(right_curverad)
# right lines info is useful when left line is none.
left_cls.radius_of_curvature.append(right_curverad)
left_curverad = np.mean(left_cls.radius_of_curvature).item()
right_curverad = np.mean(right_cls.radius_of_curvature).item()
offset = (np.mean(left_cls.line_base_pos)-np.mean(right_cls.line_base_pos)).item()
# Remove old values
last=50
left_cls.radius_of_curvature = left_cls.radius_of_curvature[-last:]
right_cls.radius_of_curvature = right_cls.radius_of_curvature[-last:]
left_cls.line_base_pos = left_cls.line_base_pos[-last:]
right_cls.line_base_pos = right_cls.line_base_pos[-last:]
return left_curverad, right_curverad, offset
img_warped = mpimg.imread('output_images/undistorted-transformed-thresholded/test2.jpg')
binary_warped = img_warped[:,:,1]
plt.imshow(binary_warped, cmap='gray')
# Calculate the radius of curvature in meters for both lane lines
left_curverad, right_curverad, offset = radii_offset(binary_warped)
print("left_r: {:>.2f} m".format(left_curverad))
print("right_r: {:>.2f} m".format(right_curverad))
print("offset: {:>.2f} m".format(offset))
def join_together(img, binary_warped):
# Add radius of curvature and offset on the frame
left_curverad, right_curverad, offset = radii_offset(binary_warped)
left_cls.detected, right_cls.detected = line_finder(img, h=2500)
if left_cls.detected:
c=left_curverad
else:
c=right_curverad
radii = 'Radii :{:>8.2f} m'.format(c)
offset= 'Offset:{:>8.2f} m'.format(offset)
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 2
fontColor = (255,255,255)
lineType = 2
bottomLeftCornerOfText1 = (100,100)
bottomLeftCornerOfText2 = (100,170)
cv2.putText(img,radii,bottomLeftCornerOfText1,font,fontScale,fontColor,lineType)
cv2.putText(img,offset,bottomLeftCornerOfText2,font,fontScale,fontColor,lineType)
# get the lane pixels
leftx, lefty, rightx, righty, _ = find_lane_pixels(binary_warped)
# acumulate x and y coordinates of lines
left_cls.allx += [leftx ]
left_cls.ally += [lefty]
right_cls.allx += [rightx]
right_cls.ally += [righty]
left_cls.currentx_mean = np.mean(leftx)
right_cls.current_mean = np.mean(rightx)
if np.abs(left_cls.currentx_mean-left_cls.lastx_mean)>3 or np.abs(left_cls.currentx_mean-left_cls.lastx_mean)<3:
leftx = np.concatenate(left_cls.allx, axis=None)
lefty = np.concatenate(left_cls.ally, axis=None)
else:
left_cls.lastx_mean = np.mean(leftx)
left_cls.allx += leftx
left_cls.ally += lefty
if np.abs(np.mean(right_cls.currentx_mean)-right_cls.lastx_mean)>3 or np.abs(np.mean(right_cls.currentx_mean)-
right_cls.lastx_mean)<3:
rightx = np.concatenate(right_cls.allx, axis=None)
righty = np.concatenate(right_cls.ally, axis=None)
else:
right_cls.lastx_mean = np.mean(rightx)
right_cls.allx += rightx
right_cls.ally += righty
left_cls.allx = left_cls.allx[-10:]
left_cls.ally = left_cls.ally[-10:]
right_cls.allx = right_cls.allx[-10:]
right_cls.ally = right_cls.ally[-10:]
# Fit a second order polynomial
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
# Generate x and y values for plotting
ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])
# x values of the last n fits of the line
left_cls.recent_xfitted.append(leftx)
right_cls.recent_xfitted.append(rightx)
left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
# Create an image to draw the lines on
warp_zero = np.zeros_like(binary_warped).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# Recast the x and y points into usable format for cv2.fillPoly()
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image
cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
newwarp =p_transfer(color_warp, dst, src)
# Combine the result with the original image
result = cv2.addWeighted(img, 1, newwarp, 0.3, 0)
return result
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip # (pip3 install imageio==2.4.1, pip3 install requests)
from IPython.display import HTML
def process_image(img):
# undistort image
undist = undistort(img, objpoints, imgpoints)
# transfer the perspective of undistorted image
binary_warped = p_transfer(undist, src, dst)
# threshold masking on image
combined_img = thmask( binary_warped)
binary_combined_img = combined_img[:,:,1]
# draw the green carpet on the road
result = join_together(img, binary_combined_img)
return result
project_output = 'output_videos/project_video.mp4'
## You may also uncomment the following line for a subclip of the first 5 seconds
#clip1 = VideoFileClip("test_videos/project_video.mp4").subclip(28,33)
clip1 = VideoFileClip("test_videos/project_video.mp4")
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
%time white_clip.write_videofile(project_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(project_output))
challenge_output = 'output_videos/challenge_video.mp4'
## You may also uncomment the following line for a subclip of the first 5 seconds
#clip1 = VideoFileClip("test_videos/project_video.mp4").subclip(28,33)
clip1 = VideoFileClip("test_videos/challenge_video.mp4")
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
%time white_clip.write_videofile(challenge_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output))